package com.tanhua.admin.listener;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.model.domain.Log;
import com.tanhua.model.mongo.Movement;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class MovementListener {
    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "tanhua.audit.queue", durable = "true"),
            exchange = @Exchange(value = "tanhua.audit.exchange", type = ExchangeTypes.TOPIC),
            key = {"audit.movement"}))
    public void listenCreate(String movementId) {
        log.info("=======================开始审核动态=======================");
        Movement movement = movementApi.findById(movementId);
        Integer state = 0;
        if (movement != null && movement.getState() == 0) {
            try {
                Map<String, String> imageScan = aliyunGreenTemplate.imageScan(movement.getMedias());
                Map<String, String> textScan = aliyunGreenTemplate.greenTextScan(movement.getTextContent());

                String imageSuggestion = imageScan.get("suggestion");
                String textSuggestion = textScan.get("suggestion");
                if ("pass".equals(imageSuggestion) && "pass".equals(textSuggestion)) {
                    state = 1;
                } else {
                    state = 2;
                }
                movementApi.update(movementId, state);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("=======================审核动态结束=======================");
    }
}
